package com.stsolutions.budgetcontroller;

import java.util.Calendar;
import java.util.List;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.stsolutions.budgetcontroller.db.DaoObject;
import com.stsolutions.budgetcontroller.db.DataBaseActions;
import com.stsolutions.budgetcontroller.db.DatabaseHelper;
import com.stsolutions.budgetcontroller.model.data.Cost;
import com.stsolutions.budgetcontroller.model.data.CostBucket;
import com.stsolutions.budgetcontroller.model.data.CostType;
import com.stsolutions.budgetcontroller.util.FormatDate;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

public class NewCostActivity extends OrmLiteBaseActivity<DatabaseHelper>
		implements OnClickListener, OnTouchListener {
	private CostBucket bucket;
	private Button addToBucketBtn;
	private Button goBackNewCostBtn;
	private Button addNewTypeButton;
	private Spinner spinner;
	private ArrayAdapter<CostType> adapter;
	private List<CostType> adapterItems;
	private Integer bucketIndex;
	private EditText pickCostDate;
	
	private static final int DATE_DIALOG_ID = 0;
	protected final String LOG_TAG = getClass().getSimpleName();
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.DATE, dayOfMonth);
			cal.set(Calendar.MONTH, monthOfYear);
			cal.set(Calendar.YEAR, year);
			pickCostDate.setText(FormatDate.formatDate(cal.getTime()));
		}
	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newcost);
		pickCostDate = (EditText) findViewById(R.id.costDateTextField);
		pickCostDate.setText("click to pick a date");
		pickCostDate.setOnTouchListener(this);
		// getting right bucket:
		Bundle extras = getIntent().getExtras();
		bucketIndex = extras.getInt("costBucketSelected");
		bucket = (CostBucket) getHelper().doDataBaseAction(
				DataBaseActions.ACTION_GET_ITEM_BY_ID, bucketIndex, null,
				DaoObject.COST_BUCKET);
		spinner = initSpinner();

		addToBucketBtn = (Button) findViewById(R.id.addToBucketBtn);
		goBackNewCostBtn = (Button) findViewById(R.id.goBackNewCostBtn);
		addNewTypeButton = (Button) findViewById(R.id.addCostTypeBtn);

		goBackNewCostBtn.setOnClickListener(this);
		addToBucketBtn.setOnClickListener(this);
		addNewTypeButton.setOnClickListener(this);

	}

	@SuppressWarnings("unchecked")
	private Spinner initSpinner() {
		adapterItems = (List<CostType>) getHelper()
				.doDataBaseAction(DataBaseActions.ACTION_GET_ALL, null, null,
						DaoObject.COST_TYPE);
		adapter = new ArrayAdapter<CostType>(this,
				android.R.layout.simple_spinner_item, adapterItems);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner = (Spinner) findViewById(R.id.costTypeSpinner);
		spinner.setAdapter(adapter);
		return spinner;
	}

	private Cost parseCostData() {
		Cost cost = new Cost();
		EditText costValueText = (EditText) findViewById(R.id.costValueTextField);
		EditText costDescriptionText = (EditText) findViewById(R.id.costDescriptionTextField);

		int itemPosition = spinner.getSelectedItemPosition();
		CostType costType = (CostType) spinner.getItemAtPosition(itemPosition);
		Log.i(LOG_TAG, "setting cost type with id: " + costType.getCostTypeId());

		// New Cost Set
		Log.i(LOG_TAG, "setting cost type: " + costType);
		cost.setCostDescription(costDescriptionText.getText().toString());
		cost.setCostType(costType);
		// formatting date
		String date = pickCostDate.getText().toString();
		cost.setCostDate(FormatDate.getDateObject(date));
		// end formatting
		cost.setCostValue(Double
				.parseDouble(costValueText.getText().toString()));
		// End of cost set

		// Clearing fields value to ""
		clearEditTextFields(costValueText);
		pickCostDate.setText("click to pick a date");
		clearEditTextFields(costDescriptionText);

		return cost;
	}

	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			Calendar cal = Calendar.getInstance();
			return new DatePickerDialog(this, mDateSetListener,
					cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
					cal.get(Calendar.DATE));
		}
		return null;
	}

	private void clearEditTextFields(EditText editText) {
		editText.setText("");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.goBackNewCostBtn: {
			Intent showCosts = new Intent(this, ShowCostsActivity.class);
			showCosts.putExtra("costBucketSelected", bucket.getCostBucketId());
			startActivity(showCosts);
			break;
		}
		case R.id.addToBucketBtn: {
			Cost cost = parseCostData();
			cost.setCostBucket(bucket);
			Log.i(LOG_TAG, "adding cost: " + cost.toString());
			getHelper().doDataBaseAction(
					DataBaseActions.ACTION_SAVE_ITEM_FOREIGN, cost,
					bucket.getCosts(), DaoObject.COST);
			break;
		}
		case R.id.addCostTypeBtn: {
			createDialog();
			break;
		}

		default:
			break;
		}
	}

	private void createDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Add New Cost Type");
		alert.setMessage("Add cost type");
		final EditText input = new EditText(this);

		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String temp = input.getText().toString();
				CostType costType = new CostType();
				costType.setCostTypeName(temp);
				getHelper().doDataBaseAction(DataBaseActions.ACTION_SAVE_ITEM,
						costType, adapterItems, DaoObject.COST_TYPE);
				adapter.notifyDataSetChanged();
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				});
		alert.show();

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.costDateTextField:
			showDialog(DATE_DIALOG_ID);
			break;
		default:
			break;
		}
		return false;
	}
}
